<template>
	<view style="height: 100%">
		<u-popup zIndex='12001' overlayStyle='z-index:12000' :custom-style="{
        	'background':'transparent','height':'100%'
        }" :show="showPosterPopup" mode='center'>
			<view class="share-poster" style="width:702rpx;height:100%;overflow-y: scroll;">
				<view class="share-poster__inner">
					<image class="inner__close" @tap="closePosterPopup"
						src="https://oos-cn.ctyunapi.cn/front-end/static/marketingImg/marketing/images/delete1.png">
					</image>
					<image class="inner_bg" :src="canvasImg"></image>
					<view class="inner_btn flex-row-center" @tap="saveQrCode">保存图片到手机相册</view>
				</view>
			</view>
		</u-popup>
		<canvas :canvasId='canvasId' style='position: fixed;top:-9999px;'
			:style="{width: (poster.width||0) + 'px', height: (poster.height||0) + 'px'}"></canvas>
	</view>
</template>

<script>
	import QSCanvas from '@/js_sdk/QuShe-SharerPoster/QuShe-SharerPoster/index.js'
	var marketing_1 = require("../../../api/marketing/marketing");
	const {
		generateQrCode
	} = marketing_1
	const app = getApp()
	export default {
		components: {
		},
		data() {
			return {
				canvasImg: '',
				//生成的海报图片链接
				posterConfig: {},
				//海报配置信息
				userInfo: {},
				//用户信息
				qrcode: '', //小程序二维码链接
				poster: {
					width: 702,
					height: 1090
				},
			};
		},
		/**
		 * 组件的属性列表
		 */
		props: {
			//分享tabs的配置信息 路径和参数用于生成二维码和链接
			shareConfig: {
				type: Object,
				default: () => ({
					path: '',//页面路径
					scene: ''//页面参数
				})
			},

			// 海报id
			canvasId: {
				type: String,
				default: 'canvasId'
			},
			// 是否显示海报
			showPosterPopup: {
				type: Boolean,
				default: false
			}
		},
		mounted() {
			this.attached();
		},
		/**
		 * 组件的方法列表
		 */
		methods: {
			// 打开海报
			openPosterPopup() {
				if (this.canvasImg) {
					this.$emit('open')
				} else {
					console.log('获取小程序码，生成海报')
					// this.init()
					this.generateQrCode(this.init)
				}
			},
			async init() {
				const poster = this.poster
				const devicePixelRatio = uni.getSystemInfoSync().devicePixelRatio
				// let bg = '../../../../static/bg.png'
				// let qrcod = '../../../../static/code.png'
				let qrcod = this.qrcode
				// let bg = 'https://oos-cn.ctyunapi.cn/front-end/static/marketingImg/marketing/images/lp_hb_bg.png'
				let bg = 'https://oos-cn.ctyunapi.cn/front-end/static/marketingImg/marketing/images/h5.png'
				console.log(qrcod,'图片')
				console.log(devicePixelRatio, '信息')
				const qsc = new QSCanvas({
					width: poster.width,
					height: poster.height,
					canvasId: this.canvasId,
					asyncDrawMode: true
				}, this)

				await qsc.drawImg({
					val: bg,
					x: 0,
					y: 0,
					mode: 'widthFixe',
					width: 702,
					height: 1090,
				})

				
				await qsc.drawImg({
					val: qrcod,
					x: 250,
					y: 680,
					mode: 'widthFixe',
					width: 200,
					height: 200,
				})

				// qsc.savePaintbrush()
				await qsc.draw()
				let canvasImg = await qsc.toImage({
					fileType: 'png',
					x: 0,
					y: 0,
					quality: 0.5,
					width: poster.width,
					height: poster.height,
					destWidth: poster.width * devicePixelRatio,
					destHeight: poster.height * devicePixelRatio,
				})
				this.chooseavatar(canvasImg)
				// this.canvasImg = canvasImg
				// this.$emit('open')
				// app.hideLoading()
				console.log(canvasImg, '这是图片路径')

			},
			chooseavatar(file) {
				let that = this
                uni.uploadFile({
                    url: getApp().globalData.URL + '/member-service/common/upload',
                    filePath: file,
                    name: 'file',
                    formData: { user: 'test' },
                    success: res=> {
						console.log('上传成功', res);
                        let data = JSON.parse(res.data)
                        if (data.code == 0) {
							that.canvasImg = data.data
							that.$emit('open')
							app.hideLoading()

							console.log(that.canvasImg, '这是完整的图片222')
                        }
                    },
                    fail() {
						console.log('上传失败');
                    }
                });
            },
			//海报点击保存到相册
			saveQrCode() {
				if (this.canvasImg) {
					console.log('保存海报',this.canvasImg)
					app.showLoading({
						title:'保存中'
					})
					this.saveImg(this.canvasImg, 'poster')
				}
			},
			attached: function() {
				// 获取用户信息
				this.getUserInfo();
			},


			// 获取用户信息
			getUserInfo() {
				let userInfo = uni.getStorageSync('userInfo') || {};
				this.setData({
					userInfo
				});
			},

			// 关闭海报弹窗
			closePosterPopup(status) {
				this.$emit('close');
			},
			
			// 获取保存到相册
			getWritePhotosAlbumSetting(fn) {
				let that = this;
				uni.getSetting({
					// 获取权限信息
					success: (response) => {
						if (!response.authSetting['scope.writePhotosAlbum']) {
							uni.authorize({
								scope: 'scope.writePhotosAlbum',
								success() {
									if (fn) {
										fn();
									}
								},
								fail() {
									if (uni.openSetting) {
										that.openSetting(fn);
									}
									return;
								}
							});
						} else {
							if (fn) {
								fn();
							}
						}
					}
				});
			},
			// 设置权限
			openSetting(fn) {
				uni.showModal({
					title: '提示',
					content: '请打开添加到相册',
					showCancel: true,
					cancelText: '取消',
					confirmText: '确定',
					success: (res) => {
						if (res.confirm) {
							uni.openSetting({
								success(res) {
									console.log(res);
									if (res.authSetting['scope.writePhotosAlbum']) {
										if (fn) {
											fn();
										}
									} else {
										uni.showToast({
											title: '需要保存到相册的权限',
											icon: 'none',
											duration: 2000
										});
									}
								}
							});
						} else if (res.cancel) {
							uni.showToast({
								title: '需要保存到相册的权限',
								icon: 'none',
								duration: 2000
							});
						}
					}
				});
			},




			// 获取小程序二维码
			async generateQrCode(fn) {
				app.showLoading()
				let {
					path,
					scene
				} = this.shareConfig;
				console.log(path, scene);
				if (!path) {
					return;
				}
				let envVersion = app.getEnvVersion()
				// 开发工具设置成为体验版
				if(envVersion == 'develop'){
					envVersion='trial'
				}
				try {
					let res = await generateQrCode({
						page: path.slice(1),
						scene,
						envVersion,
						checkPath: envVersion == 'release'
					});
					if (res.code == 200) {
						this.qrcode = res.data
						console.log(this.qrcode,'这是二维码链接')
						fn && fn()
					}
				} catch (error) {}
			},
			
			saveImg(qrcode, name) {
				console.log(qrcode, name)
				let that = this
				// #ifdef APP-PLUS
				uni.getImageInfo({
					src: qrcode,
					success: function(res) {
						let filePath = res.path;
						console.log(res);
						console.log(filePath, 'filePath');
						uni.saveImageToPhotosAlbum({
							filePath,
							success(res) {
								console.log('res', res);
								uni.showToast({
									title: '已保存到相册',
									icon: 'success',
									duration: 3000
								});
							},
							fail: function(err) {
								uni.showModal({
									title: '提示',
									content: '请在设置打开读写手机存储权限',
									showCancel: true,
									cancelText: '取消',
									confirmText: '确定',
									success: (res) => {
										if (res.confirm) {
											uni.openAppAuthorizeSetting()
										} else if (res.cancel) {
											uni.showToast({
												title: '需要保存到相册的权限',
												icon: 'none',
												duration: 2000
											});
										}
									}
								});
							},
							complete(){
								app.hideLoading()
							}
						});
					}
				});
				// #endif


				// H5 保存图片
				// #ifdef H5
				const imgUrl = qrcode;
				if (window.navigator.msSaveOrOpenBlob) {
					console.log(window.navigator.msSaveOrOpenBlob, 132)
					let bstr = atob(imgUrl.split(",")[1]);
					let n = bstr.length;
					let u8arr = new Uint8Array(n);
					while (n--) {
						u8arr[n] = bstr.charCodeAt(n);
					}
					let blob = new Blob([u8arr]);
					window.navigator.msSaveOrOpenBlob(blob, name);
				} else {
					console.log('下载')
					let a = document.createElement("a");
					a.href = imgUrl;
					a.setAttribute("download", name);
					// document.body.appendChild(a);
					a.click();
					// document.body.removeChild(a);
				}
				app.hideLoading()
				// #endif

				// H5 微信小程序
				// #ifdef MP-WEIXIN
				that.getWritePhotosAlbumSetting(() => {
					console.log('lllaf推广子组件保存')
					uni.downloadFile({
						url: qrcode,
						success: function(res) {
							let filePath = res.tempFilePath;
							console.log(res);
							console.log(filePath, 'filePath');
							uni.saveImageToPhotosAlbum({
								filePath,
								success(res) {
									console.log('res', res);
									uni.showToast({
										title: '已保存到相册',
										icon: 'success',
										duration: 3000
									});
								},
								fail: function(err) {
									uni.showToast({
										title: err.errMsg,
										icon: 'none',
										duration: 3000
									});
								},
								complete(){
									app.hideLoading()
								}
							});
						},
						fail: (err) => {
							console.log('下载文件失败share222', err);
						}
					});
				});
				// #endif
			}

		},
		created: function() {}
	}
</script>
<style lang="less">
	@import '../../../commin/flex.less';

	.share-poster {
		&__inner {
			padding: 73rpx 0 40rpx 0;
			width: 703rpx;
			position: relative;
			transform: scale(0.8);

			.inner__close {
				width: 44rpx;
				height: 44rpx;
				position: absolute;
				right: 0;
			}

			.inner_bg {
				width: 703rpx;
				height: 1123rpx;
				background: #fff;
				margin-top: 70rpx;
				border-radius: 16rpx;
				margin-bottom: 64rpx;
			}

			.inner_btn {
				width: 680rpx;
				height: 88rpx;
				background: #000000;
				border-radius: 44rpx;
				font-weight: bold;
				color: #ffffff;
			}
		}
	}
</style>
